local utils = import '../utils.libsonnet';

{
  Zookeeper(name, _values)::
    local values = std.mergePatch(
      (import 'values.libsonnet'),
      _values,
    );

    local args = if values.size > 1 then
      [
        {
          id: std.toString(id),
          name: name + values.infix + std.toString(id),
        }
        for id in std.range(1, values.size)
      ]
    else
      [
        {
          id: '1',
          name: name,
        },
      ];

    [
      utils.Service(
        arg.name,
        std.mergePatch(values.service, {
          ports: {
            tcp: [2181, 2888, 3888],
          },
        })
      )
      for arg in args
    ] +

    [
      utils.PersistentVolumeClaim(
        arg.name + '-data',
        values.storage,
      )
      for arg in args
    ] +

    [
      utils.StatefulSet(arg.name, std.mergePatch(
        values,
        {
          env: utils.Envs(values.env {
            ZKAUTOCFG_MYID: arg.id,
            ZKAUTOCFG_SERVERS: std.join(',', [
              arg.name + ':2888:3888'
              for arg in args
            ]),
          }),
          podLabels: {
            service: name,
          },
          volumes: [
            {
              name: 'vol-data',
              persistentVolumeClaim: {
                claimName: arg.name + '-data',
              },
            },
          ],
          volumeMounts: [
            {
              name: 'vol-data',
              mountPath: '/data',
            },
          ],
        }
      ))
      for arg in args
    ],
}
